package com.example.runningdemo.designModel.factory.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author kw
 * @program running
 * @description 动态代理实现类
 * @create 2024 - 08 - 10 12:06
 **/
public class DynamicInvocationHandlerImpl implements InvocationHandler {

    private Object target;

    public DynamicInvocationHandlerImpl(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("调用开始处理");
        Object invoke = method.invoke(target, args);
        System.out.println("调用结束处理");
        return invoke;
    }

    public static void main(String[] args) {
        UserDao userDao = new UserDaoImpl();
        DynamicInvocationHandlerImpl invocationHandler = new DynamicInvocationHandlerImpl(userDao);
        ClassLoader classLoader = userDao.getClass().getClassLoader();
        Class<?>[] interfaces = userDao.getClass().getInterfaces();
        UserDao proxyInstance = (UserDao) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
        proxyInstance.save();
    }
}
